__file__ = 'A13.py'
__author__ = 'Jerry Liu'
__date__ = '2016-04-14'

"""
    问题：用 Python 写一个爬图片的程序
    常用库：BeautifulSoup
"""
from bs4 import BeautifulSoup
import urllib.request
from os.path import dirname, exists
from os import makedirs

# 获取图片的url连接
def getImg(url):
    htmlsource = urllib.request.urlopen(url).read()
    bs = BeautifulSoup(htmlsource, "html.parser")
    imglist = bs.find_all('img', attrs={"class": "origin_image"})
    for i in range(len(imglist)):
        link = imglist[i]
        download(link.get('data-original'))

# 保存到本地
def download(url):
    print(url)
    file = 'd://爬虫/知乎壁纸' + url[url.rindex('/'):]
    # 文件处理
    ldir = dirname(file)
    if not exists(ldir):
        makedirs(ldir)

    urllib.request.urlretrieve(url, file)

if __name__ == '__main__':
    getImg('https://www.zhihu.com/question/24340705')
